﻿using CMS.Models;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace CMS.ViewModel
{
    public class AddCargoViewModel:ViewModelBase
    {
       public AddCargoViewModel()
        {
            //显示物资类型把另外一个表数据传递到这里
            CargoTypes=new CargoTypeProvider().Select();
            UnitTypes = new UnitTypeProvider().Select();
        }
        private Cardgo cardgo = new Cardgo();
        /// <summary>
        /// 当前物资类型
        /// </summary>
        public Cardgo Cardgo
        {
            get { return cardgo; }
            set { cardgo = value; RaisePropertyChanged(nameof(Cardgo)); }
        }
        /// <summary>
        /// 所有物资类型列表
        /// </summary>
        private List<CargoType> cargoTypes = new List<CargoType>();
        public List<CargoType> CargoTypes
        {
            get { return cargoTypes; }
            set { cargoTypes = value; RaisePropertyChanged(nameof(CargoTypes));}
        }
        /// <summary>
        /// 单位类型列表
        /// </summary>
        private List<UnitType> unitTypes = new List<UnitType>();
        public List<UnitType> UnitTypes
        {
            get { return unitTypes; }
            set { unitTypes = value; RaisePropertyChanged(nameof(UnitTypes)); }
        }
        /// <summary>
        /// 关闭窗体
        /// </summary>
        public RelayCommand<Window> AddCargoCloseCommand
        {
            get
            {
                return new RelayCommand<Window>((arg) =>
                {
                   if(arg==null) return;
                   arg.Close();
                });
            }
        }
        /// <summary>
        /// 添加新的物资类型
        /// </summary>
        public RelayCommand<Window> AddCargoCommand
        {
            get
            {
                return new RelayCommand<Window>((arg) =>
                {
                    if (string.IsNullOrEmpty(cardgo.Name)||string.IsNullOrEmpty(cardgo.TypeName)||string.IsNullOrEmpty(cardgo.UnitName)) return;
                    //给Typeld赋值然后在删除时候判断类型有没有
                    cardgo.Typeld=this.cargoTypes.FirstOrDefault(t=>t.Name == cardgo.TypeName).Id;
                    cardgo.UnitId = this.unitTypes.FirstOrDefault(t => t.Name == cardgo.UnitName).Id;
                    cardgo.InserDate = DateTime.Now;
                    cardgo.MenberId = AppData. Instance.CurrentUser.Id;
                    cardgo.MenberName = AppData. Instance. CurrentUser.Name;
                    var count = new CargoProvider().Insert(cardgo);
                    if (count == 0)
                    {
                        MessageBox.Show("添加失败");
                    }
                    else
                    {
                        arg.Close();
                    }
                });
            }
        }
    }
}
